package com.shundr.shipper.truck;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.InfoWindow.OnInfoWindowClickListener;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfigeration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult.AddressComponent;
import com.shundr.shipper.R;
import com.shundr.shipper.common.util.BaiduMapManager;
import com.shundr.shipper.frame.util.LLogger;
import com.shundr.shipper.frame.util.StringUtil;
import com.shundr.shipper.truck.model.UserTrackInfo;

public class UserTruckMapFragment extends Fragment implements OnClickListener {
	
	private View mView;
	private Button requestLocButton;

	private RelativeLayout mLayoutNoContent;
	private TextView tvNoContent;

	// 定位相关
	private MapView mMapView;
	private BaiduMapManager mMapManager;

	boolean isFirstLoc = true;// 是否首次定位

	private BitmapDescriptor icon_start = BitmapDescriptorFactory
			.fromResource(R.drawable.icon_st);
	private BitmapDescriptor icon_geo = BitmapDescriptorFactory
			.fromResource(R.drawable.icon_geo);
	private BitmapDescriptor icon_end = BitmapDescriptorFactory
			.fromResource(R.drawable.icon_en);
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initData();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_location, null);
		initView();
		return mView;
	}

	private void initView() {
		requestLocButton = (Button) mView.findViewById(R.id.btn_location_mode);
		requestLocButton.setText("普通");
		requestLocButton.setOnClickListener(btnClickListener);
		RadioGroup group = (RadioGroup) mView.findViewById(R.id.radioGroup);
		group.setOnCheckedChangeListener(radioButtonListener);
		mLayoutNoContent = (RelativeLayout) mView.findViewById(R.id.layout_no_content);
		tvNoContent = (TextView) mView.findViewById(R.id.tv_no_content);
	}

	private void initData() {
		// 地图初始化
		mMapView = (MapView) mView.findViewById(R.id.bmapView);
		mMapManager = new BaiduMapManager(getActivity(), mMapView.getMap());
		mMapManager.initMap();
		mMapManager.setMapStatus(7);
		mMapManager.setLocationListener(new MyLocationListenner());
		mMapManager.startLocation();
		mMapView.getMap().setOnMarkerClickListener(new OnMarkerClickListener() {

			@Override
			public boolean onMarkerClick(Marker marker) {
				// 获得marker中的数据
				final UserTrackInfo info = (UserTrackInfo) marker.getExtraInfo().get("info");
				InfoWindow mInfoWindow;
				// 生成一个TextView用户在地图中显示InfoWindow
				TextView location = new TextView(getActivity());
				location.setBackgroundResource(R.drawable.bg_location_tips);
				location.setPadding(30, 20, 30, 50);
				location.setTextColor(Color.WHITE);
				if(StringUtil.isNull(info.getCity())){
					location.setText(info.getCity());
				}else{
					location.setText(info.getCity() + "  " + info.getUpdateTime());
				}
				// 将marker所在的经纬度的信息转化成屏幕上的坐标
				final LatLng ll = marker.getPosition();
				Point p = mMapView.getMap().getProjection().toScreenLocation(ll);
				p.y -= 47;
				LatLng llInfo = mMapView.getMap().getProjection()
						.fromScreenLocation(p);
				// 为弹出的InfoWindow添加点击事件
				mInfoWindow = new InfoWindow(location, llInfo,
						new OnInfoWindowClickListener() {

							@Override
							public void onInfoWindowClick() {
								// 隐藏InfoWindow
								mMapView.getMap().hideInfoWindow();
							}
						});
				// 显示InfoWindow
				mMapView.getMap().showInfoWindow(mInfoWindow);
				return true;
			}
		});

		mMapView.getMap().setOnMapClickListener(new OnMapClickListener() {

			@Override
			public boolean onMapPoiClick(MapPoi arg0) {
				return false;
			}

			@Override
			public void onMapClick(LatLng arg0) {
				mMapView.getMap().hideInfoWindow();
			}
		});
	}

	/**
	 * 刷新mapView
	 * 
	 * @param infos
	 */
	public void refreshMapData(List<UserTrackInfo> infos) {
		// if(infos.size() > 0){
		// mMapView.setVisibility(View.VISIBLE);
		// mLayoutNoContent.setVisibility(View.GONE);
		try {
			List<LatLng> list = new ArrayList<LatLng>();
			mMapView.getMap().clear();
			for (int i = 0; i < infos.size(); i++) {
				UserTrackInfo info = infos.get(i);
				if(info.getLocationLat() != info.getLocationLng()){
					double lat = info.getLocationLat();
					double lng = info.getLocationLng();
					if (lat != 0 && lng != 0) {
						LatLng latLng = new LatLng(lat, lng);
						list.add(latLng);
						MarkerOptions option = new MarkerOptions().position(latLng);
						if (i == 0) {
							option.icon(icon_start);
						} else if (i == infos.size() - 1) {
							option.icon(icon_end);
						} else {
							option.icon(icon_geo);
						}
						option.title((i + 1) + "");
						Marker changeMarker = (Marker) mMapView.getMap().addOverlay(option);
						// changeMarker.setTitle("科技街");
						changeMarker.setPosition(latLng);
						Bundle bundle = new Bundle();
						bundle.putSerializable("info", info);
						changeMarker.setExtraInfo(bundle);
					}
				}
			}
			if (list.size() > 1) {
				OverlayOptions ooPolyline = new PolylineOptions().width(8)
						.color(Color.parseColor("#80c269")).points(list);
				mMapView.getMap().addOverlay(ooPolyline);
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		// }else{
		// mMapView.setVisibility(View.GONE);
		// mLayoutNoContent.setVisibility(View.VISIBLE);
		// }
	}

	OnCheckedChangeListener radioButtonListener = new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			if (checkedId == R.id.defaulticon) {
				mMapManager.changeType(BaiduMap.MAP_TYPE_NORMAL);
			}
			if (checkedId == R.id.customicon) {
				mMapManager.changeType(BaiduMap.MAP_TYPE_SATELLITE);
			}
		}
	};

	OnClickListener btnClickListener = new OnClickListener() {
		public void onClick(View v) {
			switch (mMapManager.getCurrentMode()) {
			case NORMAL:
				requestLocButton.setText("跟随");
				mMapManager.changeLocationMode(LocationMode.FOLLOWING);
				break;
			case COMPASS:
				requestLocButton.setText("普通");
				mMapManager.changeLocationMode(LocationMode.NORMAL);
				break;
			case FOLLOWING:
				requestLocButton.setText("罗盘");
				mMapManager.changeLocationMode(LocationMode.COMPASS);
				break;
			}
		}
	};

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null)
				return;
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();

			mMapView.getMap().setMyLocationData(locData);
			if (isFirstLoc) {
				// isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				mMapView.getMap().animateMapStatus(u);
				// 获取当前位置的经纬度
				LatLng latLng = new LatLng(location.getLatitude(),
						location.getLongitude());
				LLogger.e("维度 ： " + location.getLatitude() + "\n" + "经度  : "
						+ location.getLongitude());
				mMapManager.setGeoCoderResultListener(new MyGeoCoderListener());
				mMapManager.reverseLocation(latLng);
//				LocationTabActivity.mLat = location.getLatitude() + "";
//				LocationTabActivity.mLng = location.getLongitude() + "";
			}

		}

		public void onReceivePoi(BDLocation poiLocation) {

		}
	}

	public class MyGeoCoderListener implements OnGetGeoCoderResultListener {

		@Override
		public void onGetGeoCodeResult(GeoCodeResult result) {
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
				// Toast.makeText(getActivity(), "抱歉，未能找到结果  ---1",
				// Toast.LENGTH_LONG).show();
			} else {
				// Toast.makeText(getActivity(), result.getAddress() + "---1",
				// Toast.LENGTH_LONG).show();
			}
		}

		@Override
		public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
			if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
				// Toast.makeText(getActivity(), "抱歉，未能找到结果",
				// Toast.LENGTH_LONG).show();
			} else {
				AddressComponent component = result.getAddressDetail();
//				LocationTabActivity.mAddress = component.province
//						+ component.city + component.district
//						+ component.street + component.streetNumber;
			}
		}

	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	@Override
	public void onPause() {
		mMapView.onPause();
		mMapManager.stop();
		super.onPause();
	}

	@Override
	public void onResume() {
		mMapView.onResume();
		mMapManager.resume();
		super.onResume();
	}

	@Override
	public void onDestroy() {
		mMapManager.destroy();
		mMapView.onDestroy();
		mMapView = null;
		icon_start.recycle();
		icon_geo.recycle();
		icon_end.recycle();
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		default:
			break;
		}

	}
}
